const fs = require('fs');
const excel = require('node-xlsx');
const {
    httpClient
} = require('../app/lib');

let exportMenus = (datas, fileName) => {
    let map = new Map();

    datas.roles.forEach(item => {
        map.set(item, {
            name: `${item}`,
            data: [
                ['序号', '分类', '菜单名称', '页面标题', '页面链接', '所属角色']
            ]
        });
    });

    datas.datas.forEach(item => {
        if (item.items.length > 0) {
            item.items.forEach(d => {
                let roleItems = (d.RoleNmaes || '').split(',');

                for (let role of roleItems) {
                    let mapItem = map.get(role);

                    if (mapItem) {
                        mapItem.data.push([
                            mapItem.data.length,
                            item.Name,
                            d.Name,
                            d.PageTitle,
                            d.url,
                            role
                        ]);
                    }
                }
            });
        }
    });

    let sheets = Array.from(map.values());
    let navSheet = {
        name: '首页',
        data: [
            ['序号', '标题', '菜单数']
        ]
    };

    sheets.unshift(navSheet);

    for (let key of map.keys()) {
        navSheet.data.push([
            navSheet.data.length,
            `${key}`,
            (map.get(key).data || []).length - 1
        ]);
    }

    let excelBuffers = excel.build(sheets);

    fs.writeFile(`./out/${fileName}.xlsx`, excelBuffers, err => {
        if (err) {
            console.log('出现错误，错误详情：', err);
        } else {
            console.log('生成成功！');
        }
    });
};

let saveMenusData = (info, fileName) => {
    httpClient.get(`http://127.0.0.1:3006/api/cs4pl/${info.dbIndex}/${info.schema}/menus`).then(rs => {
        fs.writeFile(`../configs/datas/cs4pl/${fileName}.js`, `module.exports = ${rs.body};`, error => {
            if (error) {
                console.log(`出现错误，错误详情：${error}`);
            } else {
                console.log('菜单数据保存成功！');
            }
        }, reject => console.log(reject));
    }).catch(reason => console.log(reason));
};

/**
 * 同步菜单信息.
 */
let asyncMenuDatas = () => {
    // 开发版
    saveMenusData({
        dbIndex: 1,
        schema: 'csbr_cta'
    }, 'dev-menus');

    // 七曜
    saveMenusData({
        dbIndex: 2,
        schema: 'qiyao'
    }, 'qiyao-menus');

    // 医药四方云
    saveMenusData({
        dbIndex: 2,
        schema: 'cta'
    }, 'cta-menus');
};

// 同步菜单信息.
// asyncMenuDatas();

exportMenus(require('./datas/cs4pl/dev-menus'), '四方云功能一览(开发版)');
// exportMenus(require('../configs/datas/cs4pl/qiyao-menus'), '四方云功能一览(七曜版)');
// exportMenus(require('../configs/datas/cs4pl/cta-menus'), '四方云功能一览(医药四方云版)');